var menu_ztree;
var menu_setting = {
    data: {
        simpleData: {
            enable: true,
        }
    },
    check: {
        enable: true
    }
};

function getMenuTree() {
    //加载菜单树
    $.get("/admin/sys/menu/getMenuWithRoleInfo.do", {roleId: getQueryString("roleId")}, function (r) {
        var zNodes = [];
        $.each(r.data, function (i, menu) {
            var node = {id: menu.menuId, pId: menu.parentId, name: menu.name, checked: menu.hasOwn == 1};
            zNodes.push(node);
        });


        menu_ztree = $.fn.zTree.init($("#menus"), menu_setting, zNodes);
        //展开所有节点
        menu_ztree.expandAll(true);
    });
};

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return '';
};

function getMenus() {
    var menus = "";
    var nodes = menu_ztree.getCheckedNodes();
    $.each(nodes, function (i, treeNode) {
        if (i == 0) {
            menus = treeNode.id;
        } else {
            menus = menus + "," + treeNode.id;
        }
    });
    return menus;
}

layui.use(['form', 'layer'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    $("#addRole").click(function () {
        var jsondata = {
            roleId: $("#roleId").val(),
            roleName: $("#roleName").val(),
            remark: $("#remark").val(),
            menuIds: getMenus()
        };
        $.ajax({
            type: 'post',
            url: "/admin/sys/role/save.do",
            data: JSON.stringify(jsondata),
            async : false,
            success: function (res) {
                if (res.code == 0) {
                    layer.msg("操作成功！");
                    layer.closeAll("iframe");
                    // 刷新父页面
                    parent.location.reload();
                    form.render();
                } else {
                    layer.msg(res.msg);
                }
            },
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
        });
    });

    function initMenuTree() {
        getMenuTree();
        form.render();
    }

    initMenuTree();
});
